#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>

#include <windows.h>

#include "include/log.h"
#include "include/pointers.h"
#include "include/botdata.h"

int
LogOpen(struct BotData *botData, char *location, char *fileName)
{
    FILE *fileHandle;
    char *fullPath;
    char *expandedLocation = getenv(location);
    
    if(expandedLocation == NULL)
    {
        MessageBox(NULL, "Failed to expand environment variable", NULL, MB_OK | MB_ICONERROR);
        return 1;
    }

    fullPath = malloc(strlen(expandedLocation) + strlen(fileName) + 2); /* 2 = \0 + \\ */
    if(fullPath == NULL)
    {
        MessageBox(NULL, "Failed to allocate memory", NULL, MB_OK | MB_ICONERROR);
        return 1;
    }

    sprintf(fullPath, "%s\\%s", expandedLocation, fileName);
    fileHandle = fopen(fullPath, "a+t");
    free(fullPath);
    if(fileHandle == NULL)
    {
        MessageBox(NULL, "Failed to open file", NULL, MB_OK | MB_ICONERROR);
        return 1;
    }
    botData->logFile = fileHandle;
    return 0;
}

int
LogClose(struct BotData *botData)
{
    return fclose(botData->logFile);
}

/* THIS FUNCTION IS NOT THREAD SAFE */
int
LogWrite(struct BotData *botData, char *logFormat, ...)
{
    va_list args;
    time_t epoch;
    char timeStamp[40] = {0};

    va_start(args, logFormat);
    time(&epoch);
    strftime(timeStamp, 39, "[ %c ] ", localtime(&epoch));
    fprintf(botData->logFile, "%s", timeStamp);
    vfprintf(botData->logFile, logFormat, args);
    fputs("\n", botData->logFile);
    fflush(botData->logFile);
    va_end(args);

    return 0;
}

void
LogPlayer(struct BotData *botData)
{
        struct RomBase *base = *BASE_PTR;
        if(base->player != NULL)
        {
            LogWrite(botData, "Player log:");
            LogWrite(botData, "We are in game with character %s (%s) (%s)",
                     base->player->name  == NULL ? "'no name'" : base->player->name,
                     base->player->title == NULL ? "no title"  : base->player->title,
                     base->player->guild == NULL ? "no guild"  : base->player->guild);
            
            LogWrite(botData, "Class %u Level %u (%u/%u power)",
                     base->player->class1,
                     base->player->level1,
                     base->player->power1,
                     base->player->power1Max);
            LogWrite(botData, "Class %u Level %u (%u/%u power)",
                     base->player->class2,
                     base->player->level2,
                     base->player->power2,
                     base->player->power2Max);
        }
        else
        {
            LogWrite(botData, "Player log: unable to read player data");
        }
}
